package com.mikufufu.blog.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mikufufu.blog.common.entity.AjaxResult;
import com.mikufufu.blog.common.entity.Query;
import com.mikufufu.blog.model.entity.User;
import com.mikufufu.blog.security.utils.AuthUtils;
import com.mikufufu.blog.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mikufufu.blog.utils.EncryptionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/admin/user")
@Api(tags = "用户接口")
public class UserAdminController {

    @Autowired
    private UserService userService;

    @GetMapping("/detail")
    @ApiOperation(value = "查询用户详情")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    public AjaxResult<User> detail(Integer id) {
        User user = userService.getById(id);
        user.setPassword(null);
        return AjaxResult.data(user);
    }

    /**
     * 通过token查询用户数据
     * @return 用户数据
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取当前登录用户的详情")
    public AjaxResult<User> getUserInfo() {
        Integer id = AuthUtils.getUserId();
        User user = userService.getById(id);
        user.setPassword(null);
        return AjaxResult.data(user);
    }

    @GetMapping("/page")
    @ApiOperation(value = "获取用户列表")
    public AjaxResult<IPage<User>> page(Query query) {
        return AjaxResult.data(userService.page(query.getPage(),new LambdaQueryWrapper<User>().eq(User::getStatus, 0)));
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    public AjaxResult<Boolean> add(@RequestBody User user) {
        String password = EncryptionUtils.sha256(user.getPassword());
        user.setPassword(password);
        return AjaxResult.data(userService.save(user));
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新用户")
    public AjaxResult<Boolean> update(@RequestBody User user) {
        return AjaxResult.data(userService.updateById(user));
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    public AjaxResult<Boolean> delete(Integer id) {
        return AjaxResult.data(userService.removeById(id));
    }

    @GetMapping("/generateInvitationCode")
    @ApiOperation(value = "获取邀请码")
    public AjaxResult<String> generateInvitationCode() {
        return AjaxResult.data(userService.generateInvitationCode());
    }

    @GetMapping("/export")
    @ApiOperation(value = "导出用户数据")
    public void export(HttpServletResponse response) {
        userService.export(response);
    }

}
